package mqtt

import (
	"encoding/json"
	mqttpaho "github.com/eclipse/paho.mqtt.golang"
	"miomp-terminal-suite/backend/log"
	"reflect"
)

type MQTT struct {
	Client mqttpaho.Client
}

func (mqtt *MQTT) Publish(publish *Publish, payload interface{}) error {

	if publish.PayloadType != reflect.TypeOf(payload) {
		panic("类型不正确")
	}
	payloadJsonByte, err := json.Marshal(payload)
	if err != nil {
		return err
	}

	if token := mqtt.Client.Publish(publish.Topic, publish.Qos, publish.Retained, payloadJsonByte); token.Wait() && token.Error() != nil {
		log.LOG.Error("MQTT发送消息失败", log.U.ErrorFiled(token.Error()))
		return token.Error()
	}

	return nil
}
